package com.heima.wemedia.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自媒体端拦截器
 */
@Component
public class WmTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中FeignAuthorization:feignpass ,如果是feign之间的 相互调用,直接放行
        String feignAuthorization = request.getHeader("FeignAuthorization");
        if (StringUtils.isNotBlank(feignAuthorization) && feignAuthorization.equals("feignpass")) {
            //放行
            return true;
        }

        //获取请求头中的userId
        String userId = request.getHeader("userId");
        if (StringUtils.isBlank(userId)) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //存入ThreadLocal中
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.valueOf(userId));
        WmThreadLocalUtil.setUser(wmUser);
        //放行
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal
        WmThreadLocalUtil.clear();
    }
}
